#include <stdio.h>
#include <string.h>
#include <openssl/bio.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <openssl/x509v3.h>
#include <openssl/evp.h>
#include <openssl/aes.h>

// gcc demo_openssl.c -lssl -lcrypto

int check_password_pem(char *cert_path)
{
	printf("%s\n", "check_password_pem");
	char encrypted[48] = {0};
	PEM_proc_type(encrypted, PEM_TYPE_ENCRYPTED);
	printf("zc:%s", encrypted);

	FILE *in;
	char *p;
	in = fopen(cert_path, "r");
	if (in == NULL) {
		printf("fopen error\n");
		return -1;
	}
	fseek(in, 0L, SEEK_END);
	int flen = ftell(in);
	if (flen <= 0) {
		printf("PEM file ftell error\n");
		fclose(in);
		return -1;
	}
	printf("file size is %d\n", flen);
	p = (char *)malloc(flen + 1);
	fseek(in, 0L, SEEK_SET);
	fread(p, flen, sizeof(char), in);

	if (!strstr(p, encrypted)) {
		printf("no passwdfile have passwd\n");
		fclose(in);
		return -2;
	}
	fclose(in);
	return 0;
}

int main(void)
{
	printf("debug\n");

	SSL_load_error_strings();
	ERR_load_BIO_strings();
	OpenSSL_add_all_algorithms();
	SSL_library_init();
	SSL_CTX *ctx_ssl;
	ctx_ssl = SSL_CTX_new(SSLv23_client_method());
	if (ctx_ssl == NULL) {
		printf("ssl_ctx_new error");
		return -1;
	}
	char *passwd = "chong";
	if (passwd) {
		SSL_CTX_set_default_passwd_cb_userdata(ctx_ssl, passwd);
		int ret = check_password_pem("debug.pem");
	}
	
	if (SSL_CTX_use_certificate_file(ctx_ssl, "debug.pem", SSL_FILETYPE_PEM) != 1) {
		printf("ssl certificate error\n");
		ERR_print_errors_fp(stderr);
		SSL_CTX_free(ctx_ssl);
		return -1;
	}
	printf("debug01\n");
	if (SSL_CTX_use_PrivateKey_file(ctx_ssl, "debug.pem", SSL_FILETYPE_PEM) != 1) {
		printf("SSL_CTX_use_PrivateKey_file failed!\n");
		SSL_CTX_free(ctx_ssl);
		return -1;
	} else {
		printf("debug success\n");
	}
	printf("debug00\n");
	if (!SSL_CTX_check_private_key(ctx_ssl)) {
		printf("Private key does not match the certificate public key\n");
		SSL_CTX_free(ctx_ssl);
		return -1;
	}

	SSL_CTX_free(ctx_ssl);
	printf("SSL verify cert Sucessed\n");
	return 0;
}
